from django.http import Http404
import functools

def parentpath(path):
    try:
        return path.rsplit('/', 2)[0] + '/'
    except IndexError:
        return path

def get_prop(request, propname, getter):
    if not hasattr(request, propname):
        setattr(request, propname, getter(request))
    return getattr(request, propname)

def get_page_from_path(request, path):
    if not path.startswith('/'):
        path = '/' + path
    try:
        return request.pagemagic.allpages.by_path[path]
    except KeyError:
        raise Http404('Page `%s` not found' % path)

def get_parentpage_from_path(request, path):
    return get_page_from_path(request, parentpath(path))

def get_path_from_request(request):
    return request.path

get_page_from_request = functools.partial(
    get_prop,
    propname='_pagemagic_page',
    getter=lambda request: get_page_from_path(request, get_path_from_request(request))
)

get_parentpage_from_request = functools.partial(
    get_prop,
    propname='_pagemagic_parentpage',
    getter=lambda request: get_parentpage_from_path(request, get_path_from_request(request))
)
